﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net8.Helper;
using net8.Models;
using net8.Models.XiTong;
using net8.Views;
using net8.Views.XiTong;

namespace net8.Controllers.XiTong
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class XtUserController : ControllerBase
    {
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public PageReturn<UserView> GetPageList(int pageIndex, int pageSize)
        {
            int total = 0;
            var list = DbHelper.Db.Queryable<XtUser>()
                .Includes(ur => ur.RoleList)
                .Includes(ur => ur.Image)
                .ToPageList(pageIndex, pageSize, ref total, u => new UserView()
                {
                    Id = u.Id,
                    CompanyId = u.CompanyId,
                    UserName = u.UserName,
                    Avatar = u.Image,
                    IsEnable = u.IsEnable,
                    UserAvatar = new UploadFile() { Id = u.FileId, Url = u.Image.FilePath },//u.Image.FilePath
                    MobilePhone = u.MobilePhone,
                    UserEmail = u.UserEmail,
                    RoleList = u.RoleList.Select(ur => ur.RoleId).ToList()
                });
            return new PageReturn<UserView>() { Total = total, List = list };
        }

        //[HttpGet]
        //public string Login([FromQuery] LoginView model)
        //{
        //    XtUser user = DbHelper.Db.Queryable<XtUser>().First(u => u.UserName == model.UserName && u.Password == model.Password);
        //    if (user == null)
        //    {
        //        return "登录名和密码错误";
        //    }

        //    Dictionary<string, object> data = new()
        //    {
        //        { "UserId", user.Id },
        //        { "Account", user.UserName }
        //    };
        //    string token = JWTEncryption.Encrypt(data, 24 * 60);//builder.Services.AddJwt();使用
        //    return token;
        //}

        [AllowAnonymous]
        [HttpGet]
        public string Login([FromQuery] LoginView model)
        {
            XtUser user = DbHelper.Db.Queryable<XtUser>().First(u => u.UserName == model.UserName && u.Password == model.Password);
            if (user == null)
            {
                throw new Exception("登录名和密码错误");
                //return "登录名和密码错误";
            }

            string data = System.Text.Json.JsonSerializer.Serialize(new
            {
                UserId = user.Id,
                UserName = user.UserName,
                LoginId = user.LoginId,
                iss = "22",
                aud = "111",
                exp = DateTimeOffset.UtcNow.AddHours(5).ToUnixTimeSeconds()
            });
            string token = JwtHelper.Encrypt(data, "123456789123456789123456789123456789");
            return token;
        }

        [HttpPost]
        public bool Add([FromBody] UserView model)
        {
            DateTime current = DateTime.Now;
            List<XtUserRole> urList = new List<XtUserRole>();
            foreach (Guid item in model.RoleList)
            {
                urList.Add(new XtUserRole()
                {
                    Id = Guid.NewGuid(),
                    AddTime = current,
                    UpdateTime = current,
                    IsDel = false,
                    UserId = model.Id,
                    RoleId = item
                });
            }

            XtUser user = new XtUser()
            {
                Id = Guid.NewGuid(),
                AddTime = current,
                UpdateTime = current,
                IsDel = false,
                UserName = model.UserName,
                Password = "123456",
                MobilePhone = model.MobilePhone,
                CompanyId = model.CompanyId,
                FileId = model.UserAvatar.Id,
                UserEmail = model.UserEmail,
                RoleList = urList
            };

            bool result = false;
            if (model.Id == Guid.Empty)
            {
                result = DbHelper.Db.InsertNav(user)
                .Include(ur => ur.RoleList, new SqlSugar.InsertNavOptions() { OneToManyIfExistsNoInsert = true })
                .ExecuteCommand();
            }
            else
            {
                user.Id = model.Id;
                result = DbHelper.Db.UpdateNav(user)
                .Include(ur => ur.RoleList)
                .ExecuteCommand();
            }


            return result;
        }

        [HttpPost]
        public bool Update([FromBody] UserView model)
        {
            XtUser entity = DbHelper.Db.Queryable<XtUser>()
                .Includes(ur => ur.RoleList)
                .Where(u => u.Id == model.Id)
                .First();

            DateTime current = DateTime.Now;
            List<XtUserRole> urList = new List<XtUserRole>();
            foreach (Guid item in model.RoleList)
            {
                urList.Add(new XtUserRole()
                {
                    Id = Guid.NewGuid(),
                    AddTime = current,
                    UpdateTime = current,
                    IsDel = false,
                    UserId = model.Id,
                    RoleId = item
                });
            }

            entity.UpdateTime = current;
            entity.UserName = model.UserName;
            entity.RoleList = urList;
            entity.FileId = model.UserAvatar.Id;
            entity.CompanyId = model.CompanyId;

            var result = DbHelper.Db.UpdateNav(entity).Include(ur => ur.RoleList).ExecuteCommand();
            return result;
        }

        [HttpDelete]
        public void Delete(Guid id)
        {
            DbHelper.Db.DeleteNav<XtUser>(u => u.Id == id).Include(ur => ur.RoleList).ExecuteCommand();
        }

        [HttpPost]
        public void SetState([FromBody] XtUser model)
        {
            XtUser user = DbHelper.Db.Queryable<XtUser>().First(u => u.Id == model.Id);
            user.IsEnable = !user.IsEnable;
            user.LoginId = Guid.NewGuid();
            DbHelper.Db.Updateable(user).ExecuteCommand();

            CsRedisHelper.Init();
        }
    }
}
